package top.natsu.reminder.gui.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import top.natsu.reminder.common.entity.WorkConfig;
import top.natsu.reminder.common.enums.TimeType;
import top.natsu.reminder.handler.TimeRecord;
import top.natsu.reminder.util.AlertUtil;
import top.natsu.reminder.util.ConfigFileUtil;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * @Description 配置中心
 * @Author shikanatsu
 * @Date 2022/4/2 0002 11:42
 **/
public class ConfigController implements Initializable {

    @FXML
    private TextField restTime;

    @FXML
    private ChoiceBox<String> timeType;

    @FXML
    private CheckBox isTip;

    @FXML
    private Button saveButton;

    @FXML
    private TextField workTime;


    @FXML
    private TextField fullText;

    @FXML
    private TextField againTime;

    @FXML
    private CheckBox simpleTips;

    @FXML
    void doSave(ActionEvent event) {
        //check params
        String wTime = workTime.getText();
        String rTime = restTime.getText();
        String type = timeType.getValue();
        String agentTime = againTime.getText();
        if (StrUtil.isBlank(wTime) || StrUtil.isBlank(rTime)) {
            AlertUtil.alert(Alert.AlertType.ERROR, "配置错误", "请正确填写配置");
            return;
        }
        if (!NumberUtil.isNumber(wTime) || !NumberUtil.isNumber(rTime) || !NumberUtil.isNumber(agentTime)) {
            AlertUtil.alert(Alert.AlertType.ERROR, "配置错误", "时间必须为数值类型");
            return;
        }
        WorkConfig config = new WorkConfig(Integer.valueOf(wTime), TimeType.getTimeByName(type),
                Integer.valueOf(rTime), fullText.getText(), isTip.isSelected(), simpleTips.isSelected(),
                Integer.valueOf(agentTime));
        ConfigFileUtil.createConfigFile(config);
        //help gc
        config = null;
        //重新加载一下配置
        TimeRecord.getInstance().setWorkConfig(ConfigFileUtil.reloadLocalConfig());
        AlertUtil.alert(Alert.AlertType.INFORMATION, "配置保存成功~", "配置已保存,注意休息~");
    }


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        WorkConfig config = ConfigFileUtil.reloadLocalConfig();
        restTime.setText(config.getRestTime().toString());
        workTime.setText(config.getWorkTime().toString());
        isTip.setSelected(config.isShowFullTips());
        timeType.setValue(null != config.getRestTimeUnit() ? config.getRestTimeUnit().getName() : TimeType.MINUTES.getName());
        fullText.setText(config.getTips());
        simpleTips.setSelected(config.isSimpleTips());
    }

    @FXML
    void clickFull() {
        if (isTip.isSelected()) {
            simpleTips.setSelected(false);
        }
    }


    @FXML
    void clickSimpleTips() {
        if (simpleTips.isSelected()) {
            isTip.setSelected(false);
        }
    }

}
